/*
 *  Copyright (C) 2010 Matthias Buch-Kromann <mbk.isv@cbs.dk>
 * 
 *  This file is part of the MatrixParser package.
 *  
 *  The MatrixParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 * 
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.osdtsystem.matrixparser.parsers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
class ActionList<A extends Action> {
    Action[] actions;
    int size;

    ActionList(int k) {
        this.actions = new Action[k];
        clear();
    }

    int size() { return size; }

    void clear() { 
        size = 0;
        Arrays.fill(actions, null);
    }

    double worstScore() {
        return size < actions.length
                ? Double.NEGATIVE_INFINITY : actions[actions.length-1].score;
    }

    A get(int index) {
        return index >= size ? null : (A) actions[index];
    }

    void add(A action) {
        // Find position for insert
        Action swap = null, newswap = null;
        for (int i = 0; i < actions.length; ++i) {
            // Null action: just replace
            if (actions[i] == null) {
                actions[i] = action;
                ++size;
                return;
            }

            // Stop when we reach the first action with worse score
            if (swap != null) {
                newswap = actions[i];
                actions[i] = swap;
                swap = newswap;
            } else if (actions[i].score() < action.score()) {
                swap = actions[i];
                actions[i] = action;
            }
        }
    }

    List<A> asList() {
        List<A> list = new ArrayList<A>(size());
        for (int i = 0; i < size(); ++i)
            list.add(get(i));
        return list;
    }
}
